var recTraceCtrl = myApp.controller('recTraceCtrl', ['$scope', '$rootScope', 'NgTableParams', function($scope, $rootScope, NgTableParams) {
	$rootScope.firstType = Tools.permissionList[0].permissionId;
	$rootScope.secondType = Tools.permissionList[0].sonPermission[7].permissionId;
	
	$scope.form = {
		title: ''
	};
	$scope.form.inquiry = {
		curPage: 1,
		inquiryKeyword: "",
		pageList:  [],
		curPage: 1,
		totalPage: 1,
		totalRow: 0
	};

	$scope.delItem = {};

	$scope.userList = [];
	$scope.classTypeList = [];

	$scope.select = {
		createBy: {},
		classTypeId: {}
	};

	// 分页
	$scope.pageList = [];
	$scope.curPage = 1;
	$scope.totalPage = 1;
	$scope.totalRow = 0;
	var PAGESIZE = 10;

	// 提示弹层
	$scope.msg = "";
	$scope.visible = false;

	// 获取跟踪列表
	$scope.getTraceList = function(curPage) {
		var data = {
			curPage: curPage,
			pagesize: PAGESIZE,
			classTypeId: $scope.classTypeId,	
			createBy: $scope.createBy,	
			keyword: $scope.keyword,	
			traceDateEnd: $scope.traceDateEnd,
			traceDateStart: $scope.traceDateStart
		}
		commonSrv.getTraceList(data, function(result) {
			var trackList = result.data.trackList;
			var classTypeList = result.data.classTypeList;
            var userList = result.data.userList;

			for(var i in trackList) {
                // 意向班级
                trackList[i].inquiry.classTypeId = Tools.getItemById(trackList[i].inquiry.classTypeId, 'id', classTypeList);
                // 跟进人
                trackList[i].createBy = Tools.getItemById(trackList[i].createBy, 'userId', userList);
            }
			$scope.traceList = new NgTableParams({count: PAGESIZE}, { counts: [],  dataset: trackList});
			// 跟进人下拉列表
			if($scope.userList.length == 0) {
				$scope.userList = userList;
			}
			// 意向班型下拉列表
			if($scope.classTypeList.length == 0) {
				$scope.classTypeList = classTypeList;
			}
			// 获取分页信息
			var paginate = result.paginate;
			$scope.totalPage = paginate.totalPage;
			$scope.totalRow = paginate.totalRow;
			// 设置分页
			$scope.setPage(curPage);
		}, function(result) {
			if(result.status == 1) {
				alert(result.msg);
			}
		}, function() {
			$scope.$apply();
		});
	};

	// 设置分页
	$scope.setPage = function(curPage, type) {
		if(type == 'inquiry') {
			var newPageList = [];
			if (curPage < 1 || curPage > $scope.form.inquiry.totalPage) {
				alert("设置分页失败");
				return;
			}
			var SHOWSIZE = 5;
			// 总页数小于SHOWSIZE
			if($scope.form.inquiry.totalPage <= SHOWSIZE) {
				for(var i=0; i<$scope.form.inquiry.totalPage; i++) {
					newPageList.push(i+1);
				}
			// 总页数大于等于SHOWSIZE
			} else {
				if(curPage > 2) {
					// 最后5页
					if(($scope.form.inquiry.totalPage - curPage) < 2) {
						for(var i = ($scope.form.inquiry.totalPage - 5); i < $scope.form.inquiry.totalPage; i++) {
							newPageList.push(i + 1);
						}
					} else {
						for (var i = (curPage - 3); i < ((curPage + 2) > $scope.form.inquiry.totalPage ? $scope.form.inquiry.totalPage : (curPage + 2)); i++) {
	                        newPageList.push(i + 1);
	                    }
					}
				} else {
					for(var i=0; i<SHOWSIZE; i++) {
						newPageList.push(i + 1);
					}
				}
			}
	        $scope.form.inquiry.pageList = newPageList;
	        $scope.form.inquiry.curPage = curPage;
		} else {
			var newPageList = [];
			if (curPage < 1 || curPage > $scope.totalPage) {
				alert("设置分页失败");
				return;
			}
			var SHOWSIZE = 5;
			// 总页数小于SHOWSIZE
			if($scope.totalPage <= SHOWSIZE) {
				for(var i=0; i<$scope.totalPage; i++) {
					newPageList.push(i+1);
				}
			// 总页数大于等于SHOWSIZE
			} else {
				if(curPage > 2) {
					// 最后5页
					if(($scope.totalPage - curPage) < 2) {
						for(var i = ($scope.totalPage - 5); i < $scope.totalPage; i++) {
							newPageList.push(i + 1);
						}
					} else {
						for (var i = (curPage - 3); i < ((curPage + 2) > $scope.totalPage ? $scope.totalPage : (curPage + 2)); i++) {
	                        newPageList.push(i + 1);
	                    }
					}
				} else {
					for(var i=0; i<SHOWSIZE; i++) {
						newPageList.push(i + 1);
					}
				}
			}
	        $scope.pageList = newPageList;
	        $scope.curPage = curPage;
	    }
	};
	//设置当前选中页样式
    $scope.isActivePage = function (page, type) {
    	if(type == 'inquiry') {
    		return $scope.form.inquiry.curPage == page
    	} else {
    		return $scope.curPage == page;
    	}
    };
    //上一页
    $scope.previous = function (type) {
    	if(type == 'inquiry') {
    		if($scope.form.inquiry.curPage > 1) {
	        	$scope.getInquiryList($scope.form.inquiry.curPage - 1);
	        }
    	} else {
    		if($scope.curPage > 1) {
	        	$scope.getTraceList($scope.curPage - 1);
	        }
    	}
    }
    //下一页
    $scope.next = function (type) {
    	if(type == 'inquiry') {
    		if($scope.form.inquiry.curPage < $scope.form.inquiry.totalPage) {
	        	$scope.getInquiryList($scope.form.inquiry.curPage + 1);
	        }
    	} else {
    		if($scope.curPage < $scope.totalPage) {
	        	$scope.getTraceList($scope.curPage + 1);
	        }
    	}
    };

    // 筛选日期范围
    $scope.selectTrackDate = function () {
    	$scope.traceDateStart = moment($scope.trackDate.start).format('YYYY-MM-DD');
    	$scope.traceDateEnd = moment($scope.trackDate.end).format('YYYY-MM-DD');
    	$scope.getTraceList($scope.curPage);
    };
    // 筛选跟进人
    $scope.selectCreateBy = function () {
        var createBy = 0;
        if(!$scope.select.createBy || $scope.select.createBy == null) {
            createBy = 0;
        } else {
            createBy = Tools.parseValue({target: $scope.select.createBy, targetValue: $scope.select.createBy.userId, type: 'number'});
        }
        $scope.createBy = createBy;
        
        $scope.getTraceList($scope.curPage);
    };
    // 筛选意向班型
    $scope.selectClassTypeId = function() {
    	var classTypeId = 0;
        if(!$scope.select.classTypeId || $scope.select.classTypeId == null) {
            classTypeId = 0;
        } else {
            classTypeId = Tools.parseValue({target: $scope.select.classTypeId, targetValue: $scope.select.classTypeId.id, type: 'number'});
        }
        $scope.classTypeId = classTypeId;
        
        $scope.getTraceList($scope.curPage);
    };
    // 搜索
    $scope.search = function() {
    	$scope.getTraceList($scope.curPage);
    }
    
    // 验证
    $scope.watchInquiryId = function () {
		var nullWarn = "不能为空";
        if(Tools.reg.isNull($scope.form.item.inquiryId.length)) {
            $scope.form.item.warn.inquiryId = nullWarn;
        } else {
            $scope.form.item.warn.inquiryId = "";
        }
    };
	$scope.watchTrackDate = function () {
		var nullWarn = "不能为空";
        if(Tools.reg.isNull($scope.form.item.trackDate)) {
            $scope.form.item.warn.trackDate = nullWarn;
        } else {
            $scope.form.item.warn.trackDate = "";
        }
	};
	$scope.watchPlanNextTrackDate = function () {
		var nullWarn = "不能为空";
        if(Tools.reg.isNull($scope.form.item.planNextTrackDate)) {
            $scope.form.item.warn.planNextTrackDate = nullWarn;
        } else {
            $scope.form.item.warn.planNextTrackDate = "";
        }
	};
	$scope.watchNotes = function () {
		var nullWarn = "不能为空";
        if(Tools.reg.isNull($scope.form.item.notes)) {
            $scope.form.item.warn.notes = nullWarn;
        } else {
            $scope.form.item.warn.notes = "";
        }
	};
	$scope.watchPurpose = function () {
		var nullWarn = "不能为空";
        if(Tools.reg.isNull($scope.form.item.purpose)) {
            $scope.form.item.warn.purpose = nullWarn;
        } else {
            $scope.form.item.warn.purpose = "";
        }
	};


	// 新增
	// 打开新增弹层
	$scope.openAdd = function () {
		$scope.form.title = "新增";
		$scope.form.item = {
			inquiryId: [],
			purpose: "",
			notes: "",
			planNextTrackDate: "",
			trackDate: "",
			warn: {
				inquiryId: "",
				purpose: "",
				notes: "",
				planNextTrackDate: "",
				trackDate: ""
			}
		};
		$scope.form.submit = $scope.addItem;
		$scope.showModel();
	};
	// 新增
	$scope.addItem = function() {
		// 验证
		var flag = $scope.validate();
		if(!flag) {
			alert("请修改表单");
			return;
		}

		// 1.inquiryId
    	var inquiryId = 0;
        if(!$scope.form.item.inquiryId || $scope.form.item.inquiryId == null) {
            inquiryId = 0;
        } else {
        	if($scope.form.item.inquiryId instanceof Array) {
        		var temp = $scope.form.item.inquiryId[0];
        		inquiryId = Tools.parseValue({target: temp, targetValue: temp.inquiryId, type: 'number'});
        	}
        }
        // 2.purpose
        var purpose = Tools.parseValue({target: $scope.form.item.purpose, targetValue: $scope.form.item.purpose, type: 'string'});
        // 3.notes
    	var notes = Tools.parseValue({target: $scope.form.item.notes, targetValue: $scope.form.item.notes, type: 'string'});
    	// 4.planNextTrackDate
    	var planNextTrackDate = "";
    	if($scope.form.item.planNextTrackDate && $scope.form.item.planNextTrackDate instanceof Date) {
    		planNextTrackDate = moment($scope.form.item.planNextTrackDate).format('YYYY-MM-DD hh:mm');
    	}
    	// 5.trackDate
    	var trackDate = "";
    	if($scope.form.item.trackDate && $scope.form.item.trackDate instanceof Date) {
    		trackDate = moment($scope.form.item.trackDate).format('YYYY-MM-DD');
    	}
    	var data = {
			inquiryId: inquiryId,
			notes: notes,
			planNextTrackDate: planNextTrackDate,
			purpose: purpose,
			trackDate: trackDate
    	};
    	commonSrv.addTrace(data, function(result) {
    		if(result.status == 0) {
    			$scope.msg = "新增成功";
    			$scope.visible = true;
    			$scope.getTraceList(1);
    			$scope.hideModel();
    		}
    	}, function(result) {
    		if(result.status == 1) {
    			alert(result.msg);
    		}
    	}, function() {
    		$scope.$apply();
    	});
	};

	// 修改
	// 打开修改弹层
	$scope.openEdit = function (item) {
		$scope.form.title = "编辑";
		var data = {
			trackId: item.trackId
		};
		commonSrv.editTraceForm(data, function(result) {
			if(result.status == 0) {
				$scope.form.item = result.data.track;
				$scope.form.item.warn = {
					inquiryId: "",
					purpose: "",
					notes: "",
					planNextTrackDate: "",
					trackDate: ""
				};
				// 设置潜在生
				if(!Tools.reg.isNull($scope.form.item.inquiryId)) {
					if($scope.form.item.inquiry instanceof Array) {
			    		$scope.form.item.inquiryId = $scope.form.item.inquiry;
			    	} else {
			    		$scope.form.item.inquiryId = [$scope.form.item.inquiry];
			    	}
				}
				if(!($scope.form.item.trackDate instanceof Date)) {
					$scope.form.item.trackDate = moment($scope.form.item.trackDate);
				}
				if(!($scope.form.item.planNextTrackDate instanceof Date)) {
					$scope.form.item.planNextTrackDate = moment($scope.form.item.planNextTrackDate);
				}
				$scope.form.submit = $scope.editItem;
    			$scope.showModel();
    		}
		}, function(result) {
			if(result.status == 1) {
    			alert(result.msg);
    		}
		}, function() {
			$scope.$apply();
		});
	};
	// 修改 
	$scope.editItem = function() {
		// 验证
		var flag = $scope.validate();
		if(!flag) {
			alert("请修改表单");
			return;
		}
		// 1.inquiryId
    	var inquiryId = 0;
        if(!$scope.form.item.inquiryId || $scope.form.item.inquiryId == null) {
            inquiryId = 0;
        } else {
        	if($scope.form.item.inquiryId instanceof Array) {
        		var temp = $scope.form.item.inquiryId[0];
        		inquiryId = Tools.parseValue({target: temp, targetValue: temp.inquiryId, type: 'number'});
        	}
        }
        // 2.purpose
        var purpose = Tools.parseValue({target: $scope.form.item.purpose, targetValue: $scope.form.item.purpose, type: 'string'});
        // 3.notes
    	var notes = Tools.parseValue({target: $scope.form.item.notes, targetValue: $scope.form.item.notes, type: 'string'});
    	// 4.planNextTrackDate
    	var planNextTrackDate = "";
    	if($scope.form.item.planNextTrackDate && $scope.form.item.planNextTrackDate instanceof Date) {
    		planNextTrackDate = moment($scope.form.item.planNextTrackDate).format('YYYY-MM-DD hh:mm');
    	}
    	// 5.trackDate
    	var trackDate = "";
    	if($scope.form.item.trackDate && $scope.form.item.trackDate instanceof Date) {
    		trackDate = moment($scope.form.item.trackDate).format('YYYY-MM-DD');
    	}
    	var data = {
			inquiryId: inquiryId,
			notes: notes,
			planNextTrackDate: planNextTrackDate,
			purpose: purpose,
			trackDate: trackDate,
			trackId: $scope.form.item.trackId
    	};
		commonSrv.editTrace(data, function(result) {
    		if(result.status == 0) {
    			$scope.msg = "修改成功";
    			$scope.visible = true;
    			$scope.getTraceList($scope.curPage);
    			$scope.hideModel();
    		}
    	}, function(result) {
    		if(result.status == 1) {
    			alert(result.msg);
    		}
    	}, function() {
    		$scope.$apply();
    	});
	};
	// 删除
	// 打开删除
    $scope.openDel = function(item) {
    	$scope.delItem = item;
    	$('#delModel').modal('show');
    };
    // 删除
    $scope.delTrace = function() {
    	var data = {
			trackId: $scope.delItem.trackId
		};
		commonSrv.delTrace(data, function(result) {
			if(result.status == 0) {
				$scope.msg = "删除成功";
				$scope.visible = true;
				$("#delModel").modal('hide');
				$scope.delItem = {};
                $scope.getTraceList($scope.curPage);
			}
		}, function(result) {
			if(result.status == 1) {
				alert(result.msg);
			}
			$("#delModel").modal('hide');
		}, function() {
			$scope.$apply();
		});
    };
	// 打开弹层
	$scope.showModel = function() {
		$("#formModel").modal({backdrop: 'static', keyboard: false, show: true});
	};
	// 关闭弹层
	$scope.hideModel = function() {
		$("#formModel").modal('hide');
	};
	// 提交表单，做提交表单验证，以及需要执行的方法
	$scope.validate = function() {
		var flag = false;
		$scope.watchInquiryId();
    	$scope.watchTrackDate();
    	$scope.watchPlanNextTrackDate();
    	$scope.watchNotes();
    	$scope.watchPurpose();

    	// 验证
    	if(!Tools.reg.isNull($scope.form.item.warn.inquiryId) || !Tools.reg.isNull($scope.form.item.warn.notes) || !Tools.reg.isNull($scope.form.item.warn.purpose) || !Tools.reg.isNull($scope.form.item.warn.planNextTrackDate) || !Tools.reg.isNull($scope.form.item.warn.trackDate)) {
    		flag = false;
    	} else {
    		flag = true;
    	}
    	return flag;
	};
	// 打开潜在生选择弹层
	$scope.openSelect = function() {
		$scope.form.inquiry = {
			curPage: 1,
			inquiryKeyword: "",
			pageList:  [],
			curPage: 1,
			totalPage: 1,
			totalRow: 0
		};
		$scope.getInquiryList($scope.form.inquiry.curPage, function(result) {
			$("#selectModel").modal({backdrop: 'static', keyboard: false, show: true});
		});
	};
	// 获取潜在生列表
    $scope.getInquiryList = function(curPage, cb) {
    	var data = {
    		channelId: 0,
			curPage: curPage,
			isMy: 0,
			keyword: $scope.form.inquiry.inquiryKeyword,
			pagesize: PAGESIZE,
			searchTraceDateTypeId: 0,	
			status:	0,	
			tagIds: "",	
			traceDateEnd: "",	
			traceDateStart: ""
    	};
    	commonSrv.getInquiryList(data, function(result) {
    		if(result.status == 0) {
    			$scope.form.inquiry.allowSubmit = true;
    			var inquiryList = result.data.inquiryList;
	    		for(var i in inquiryList) {
	    			inquiryList[i].isSelected = false;
	    		}
    			$scope.inquiryList = new NgTableParams({count: PAGESIZE}, { counts: [],  dataset: inquiryList});
    			// 获取分页信息
				var paginate = result.paginate;
				$scope.form.inquiry.totalPage = paginate.totalPage;
				$scope.form.inquiry.totalRow = paginate.totalRow;
				// 设置分页
				$scope.setPage(curPage, 'inquiry');
    			if(typeof cb == 'function') {
    				cb(result);
    			}
    		}
    	}, function(result) {
    		if(result.status == 1) {
    			alert(result.msg);
    		}
    	}, function() {
    		$scope.$apply();
    	});
    };

    // 选择潜在生
    $scope.selectItem = function(item) {
    	for(var i in $scope.inquiryList.data) {
    		$scope.inquiryList.data.isSelected = false;
    	}
    	item.isSelected = true;
    	$scope.form.inquiry.selectedItem = item;
    	$scope.form.inquiry.allowSubmit = false;
    };
    // 确认选择
    $scope.submitSelect = function() {
    	if($scope.form.inquiry.selectedItem instanceof Array) {
    		$scope.form.item.inquiryId = $scope.form.inquiry.selectedItem;
    	} else {
    		$scope.form.item.inquiryId = [$scope.form.inquiry.selectedItem];
    	}
    	$scope.watchInquiryId();
    	$scope.close('#selectModel');
    };
	// 删除已选择潜在生
	$scope.selectedRemove = function() {
		$scope.form.item.inquiryId.pop();
		$scope.watchInquiryId();
	};
    // 关闭二级弹层
    $scope.close = function (name) {
    	Tools.hideModal(name);
    };
    // 搜索
    $scope.searchByInquiryKeyword = function () {
    	$scope.getInquiryList(1);
    };
    // 设置初始化参数
    $scope.intiParam = function() {
    	$scope.classTypeId = 0;
		$scope.createBy = 0;

		$scope.keyword = "";
		$scope.traceDateEnd = "";
		$scope.traceDateStart = "";
		$scope.trackDate = {
			start: "",
			end: ""
		};
		$scope.getTraceList(1);
    };

	// 初始化
	function init() {
		$scope.intiParam();
		$(document).ready(function() {
			// console.log($rootScope.secondType);
		});
	}
	init();
}]);